// DeepSeek API配置
const DEEPSEEK_API_KEY = "sk-caafe56d570a4731b274603677c02a3d";
// 使用代理路径
const DEEPSEEK_API_URL = "/deepseek/chat/completions";

// 模拟对话列表数据
const mockConversations = [
	{
		id: "1",
		title: "如何学习Vue.js",
		createdAt: "2024-10-28 10:30:00",
		messages: [
			{ role: "user", content: "如何学习Vue.js？" },
			{ role: "assistant", content: "学习Vue.js可以从官方文档开始，然后通过实践项目来巩固知识。" },
		],
	},
	{
		id: "2",
		title: "JavaScript闭包问题",
		createdAt: "2024-10-29 14:20:00",
		messages: [
			{ role: "user", content: "什么是JavaScript闭包？" },
			{ role: "assistant", content: "闭包是指函数能够访问其词法作用域之外的变量的能力。" },
		],
	},
	{
		id: "3",
		title: "CSS布局技巧",
		createdAt: "2024-10-30 09:15:00",
		messages: [
			{ role: "user", content: "有哪些常用的CSS布局技巧？" },
			{ role: "assistant", content: "常用的CSS布局技巧包括Flexbox、Grid、定位等。" },
		],
	},
];

// API封装类
class ChatAPI {
	// 获取对话列表
	static async getConversations() {
		// 模拟API延迟
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve({
					success: true,
					data: mockConversations,
				});
			}, 500);
		});
	}

	// 创建新对话
	static async createConversation(title = "新对话") {
		const newConversation = {
			id: Date.now().toString(),
			title,
			createdAt: new Date().toISOString(),
			messages: [],
		};

		mockConversations.unshift(newConversation);

		return new Promise((resolve) => {
			setTimeout(() => {
				resolve({
					success: true,
					data: newConversation,
				});
			}, 300);
		});
	}

	// 发送消息到DeepSeek API（流式响应）
	static async sendMessageStream(message, conversationId = null, onChunk = null, signal = null) {
		try {
			const fetchOptions = {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bearer ${DEEPSEEK_API_KEY}`,
				},
				body: JSON.stringify({
					model: "deepseek-chat",
					messages: [
						{
							role: "user",
							content: message,
						},
					],
					stream: true,
					temperature: 0.7,
					max_tokens: 2048,
				}),
			};

			// 如果提供了 signal，添加到 fetch 选项
			if (signal) {
				fetchOptions.signal = signal;
			}

			const response = await fetch(DEEPSEEK_API_URL, fetchOptions);

			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const reader = response.body.getReader();
			const decoder = new TextDecoder();
			let fullContent = "";

			while (true) {
				const { done, value } = await reader.read();
				if (done) break;

				const chunk = decoder.decode(value);
				const lines = chunk.split("\n");

				for (const line of lines) {
					if (line.startsWith("data: ") && line !== "data: [DONE]") {
						try {
							const data = JSON.parse(line.slice(6));
							if (data.choices && data.choices[0] && data.choices[0].delta && data.choices[0].delta.content) {
								const content = data.choices[0].delta.content;
								fullContent += content;
								if (onChunk) {
									onChunk(content, fullContent);
								}
							}
						} catch (e) {
							// 忽略解析错误
						}
					}
				}
			}

			return {
				success: true,
				data: {
					role: "assistant",
					content: fullContent,
				},
			};
		} catch (error) {
			console.error("DeepSeek API调用失败:", error);
			return {
				success: false,
				error: "API调用失败，请检查网络连接或API密钥",
			};
		}
	}

	// 发送消息到DeepSeek API（兼容旧版本）
	static async sendMessage(message, conversationId = null) {
		return this.sendMessageStream(message, conversationId);
	}

	// 获取特定对话的详情
	static async getConversationDetail(conversationId) {
		const conversation = mockConversations.find((conv) => conv.id === conversationId);

		return new Promise((resolve) => {
			setTimeout(() => {
				if (conversation) {
					resolve({
						success: true,
						data: conversation,
					});
				} else {
					resolve({
						success: false,
						error: "对话不存在",
					});
				}
			}, 300);
		});
	}

	// 删除对话
	static async deleteConversation(conversationId) {
		const index = mockConversations.findIndex((conv) => conv.id === conversationId);

		return new Promise((resolve) => {
			setTimeout(() => {
				if (index !== -1) {
					mockConversations.splice(index, 1);
					resolve({
						success: true,
						message: "删除成功",
					});
				} else {
					resolve({
						success: false,
						error: "对话不存在",
					});
				}
			}, 300);
		});
	}
}

export default ChatAPI;
